package com.twu.biblioteca.service;

import com.twu.biblioteca.dao.UserDao;

import java.io.PrintStream;
import java.util.Scanner;

public class UserService {
    private final String MESSAGE_LOGIN_FAILED = "Login failed, will exit!";
    private final String MESSAGE_TRY_AGAIN = "Wrong credential! Please try again!\n";
    private final String PROMPT_USERNAME = "Username:";
    private final String PROMPT_PASSWORD = "Password:";
    private final String PROMPT_LOGIN = "Please Login!(Press any key to continue)\n";
    private final String MESSAGE_WELCOME_BACK = "Welcome back!\n";
    private final int MAX_VERIFY_COUNT = 3;
    private UserDao userDao = new UserDao();
    private Scanner scanner = new Scanner(System.in);
    private PrintStream printStream = System.out;

    public UserService() {
        userDao.prepareData();
    }

    public boolean login() {
        promptLoginStart();

        int count = 0;
        while (count < MAX_VERIFY_COUNT) {
            String username = getUsername();
            String password = getPassword();
            if (userDao.verify(username, password)) {
                promptWelcomeBack();
                return true;
            }
            count++;
            verifyRetryCount(count);
        }
        return false;
    }

    private void verifyRetryCount(int count) {
        if (count > 2) {
            printStream.print(MESSAGE_LOGIN_FAILED);
        } else {
            promptTryAgain();
        }
    }

    private void promptWelcomeBack() {
        printStream.println(MESSAGE_WELCOME_BACK);
    }

    private void promptLoginStart() {
        printStream.print(PROMPT_LOGIN);
        scanner.nextLine();
    }

    private void promptTryAgain() {
        printStream.print(MESSAGE_TRY_AGAIN);
    }

    private String getPassword() {
        printStream.print(PROMPT_PASSWORD);
        return scanner.nextLine();
    }

    private String getUsername() {
        printStream.print(PROMPT_USERNAME);
        return scanner.nextLine();
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setScanner(Scanner scanner) {
        this.scanner = scanner;
    }

    public void setPrintStream(PrintStream printStream) {
        this.printStream = printStream;
    }
}
